package org.imooc.controller.content;

import org.imooc.constant.PageCodeEnum;
import org.imooc.dto.AdDto;
import org.imooc.service.AdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/ad")
public class AdController {

    @Autowired
    AdService adService;

    /**
     * 广告列表初始化界面
     * @return
     */
    @RequestMapping
    public String init(Model model){
        AdDto adDto = new AdDto();
        model.addAttribute("list", adService.findByPage(adDto));
        model.addAttribute("searchParam", adDto);
        return "/content/adList";
    }

    @RequestMapping("/addInit")
    public String addInit(){
        return "/content/adAdd";
    }

    @RequestMapping("modifyInit")
    public String modifyInif(Long id, Model model){
        AdDto adDto = adService.findById(id);
        model.addAttribute("modifyObj", adDto);
        return "/content/adModify";
    }

    @RequestMapping("remove")
    public String remove(Long id, Model model){
        if (adService.remove(id)){
            model.addAttribute(PageCodeEnum.KEY, PageCodeEnum.REMOVE_SUCCESS);
        }else {
            model.addAttribute(PageCodeEnum.KEY, PageCodeEnum.REMOVE_FAIL);
        }
        return "forward:/ad";
    }

    @RequestMapping("/add")
    public String add(AdDto adDto, Model model){
        if (adService.add(adDto)){
            model.addAttribute(PageCodeEnum.KEY, PageCodeEnum.ADD_SUCCESS );
        }else {
            model.addAttribute(PageCodeEnum.KEY, PageCodeEnum.ADD_FAIL);
        }
        return "/content/adAdd";
    }

    @RequestMapping("/search")
    public String search(AdDto adDto, Model model){
        model.addAttribute("list", adService.findByPage(adDto));
        model.addAttribute("searchParam", adDto);
        return "/content/adList";
    }


}